package com.house.framework.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: TODO
 * @Author: ArvinWoo
 * @Date: 2022/10/21 16:59
 * @ClassName: WebSocket
 **/
@ServerEndpoint("/webSocket/{username}")
@Slf4j
@Component
public class WebSocket {

    private static int onlineCount = 0;
    private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
    private Session session;
    private String username;

    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) {
        this.username = username;
        this.session = session;
        WebSocket.onlineCount++;
        clients.put(username, this);
        System.out.println("in user：" + username + " userCount：" + WebSocket.onlineCount);
    }

    @OnClose
    public void onClose() {
        clients.remove(username);
        WebSocket.onlineCount--;
        System.out.println("out user：" + username + " userCount：" + WebSocket.onlineCount);
    }

    @SneakyThrows
    @OnMessage
    public void onMessage(String message) {
        JSONObject jsonTo = JSONObject.parseObject(message);
        String mes = (String) jsonTo.get("message");

        if (!jsonTo.get("To").equals("All")){
            sendMessageTo(mes, jsonTo.get("To").toString());
        }else{
            sendMessageAll("send all user");
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("WebSocket发生错误：" + throwable.getMessage());
    }

    public static void sendMessageTo(String message, String To) {
        for (WebSocket item : clients.values()) {
            if(item.username.equals(To)){
                item.session.getAsyncRemote().sendText(message);
            }
        }
    }

    public static void sendMessageAll(String message) throws IOException {
        for (WebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }

}

